package com.xhb.biz.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.solon.service.impl.ServiceImpl;
import com.xhb.biz.feign.UserDataSyncService;
import com.xhb.biz.mapper.ProxyMapper;
import com.xhb.biz.po.ProxyPO;
import com.xhb.biz.po.UrlPO;
import org.noear.solon.Solon;
import org.noear.solon.aspect.annotation.Service;
import org.noear.solon.data.annotation.Tran;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class ProxyService extends ServiceImpl<ProxyMapper, ProxyPO> {

    public List<ProxyPO> getProxyList() {
        List<ProxyPO> list = super.list();
        return list;
    }


    /**
     * 首页导航分组同步
     *
     * @param userService feign 接口
     * @param headers     请求头
     */
    @Tran
    public void proxyListSync(UserDataSyncService userService, Map<String, Object> headers) {
        //<editor-fold desc="保存代理 url 的数据">
        String data = userService.getProxyUrlList(headers);
        List<UrlPO> urlPos = JSONUtil.toList(data, UrlPO.class);
        if (CollectionUtil.isEmpty(urlPos)) {
            return;
        }
        Solon.context().getBeanAsync(UrlService.class, service -> service.syncUrlData(urlPos));
        //</editor-fold>

        JSONArray dataArr = JSONUtil.parseArray(data);
        List<ProxyPO> proxyPos = new ArrayList<>(dataArr.size());
        Set<String> proxyIdSet = new HashSet<>();

        dataArr.forEach(item -> {
            JSONObject proxyJson = JSONUtil.parseObj(item);
            String proxyId = proxyJson.get("proxyId", String.class);
            if (!StringUtils.isBlank(proxyId) && !proxyIdSet.contains(proxyId)) {
                proxyIdSet.add(proxyId);
                ProxyPO proxyPo = ProxyPO.builder()
                        .id(proxyId)
                        .name(proxyJson.get("proxyName", String.class))
                        .ip(proxyJson.get("ip", String.class))
                        .port(proxyJson.get("port", Integer.class))
                        .isSpeedUp(proxyJson.get("isSpeedUp", Integer.class))
                        .build();
                proxyPos.add(proxyPo);
            }
        });
        if (CollectionUtil.isNotEmpty(proxyPos)) {
            super.saveOrUpdateBatch(proxyPos);
            // 删除已被管理端删除的旧数据
            LambdaQueryWrapper<ProxyPO> delWrapper = new LambdaQueryWrapper<>();
            delWrapper.notIn(ProxyPO::getId, proxyPos.stream().map(ProxyPO::getId).collect(Collectors.toList()));
            super.remove(delWrapper);
        }
    }

}
